#include <gst/gst.h>
#include <stdio.h>

/*
  The pipeline to create is:

  gst-launch filesrc location=music/callMeMaybe.mp3 ! mad ! audioconvert !
             rtpL16pay ! udpsink host=192.168.1.141 port=5000

  */


int main (int argc, char *argv[])
{

    /*Main object*/
    GMainLoop *loop;

    /*Elements*/
    GstElement *source,
                *mad,
                *pipeline,
                *convert,
                *rtp, /* RTP packer */
                *udp; /* UDP sender */

   

    char *audioFileName; //Contains the path of the music to play


    /* Initialize GStreamer */
    gst_init (&argc, &argv);
    loop = g_main_loop_new (NULL, FALSE);

   /*/* Check input arguments */
    if (argc != 3) { //Prints an error if there are less arguments
        g_printerr ("Usage:-f audioFilePath");
        return -1; //exit with errors
      }

    audioFileName = argv[2]; //Obtains the mp3 file path

    /* Create gstreamer elements */
    pipeline = gst_pipeline_new ("mp3 player");
    source = gst_element_factory_make ("filesrc", "filesrc");

    /* we set the input filename to the source element */
    g_object_set (G_OBJECT (source), "location", audioFileName , NULL);

    mad = gst_element_factory_make ("mad", "mad");
    convert = gst_element_factory_make("audioconvert", NULL);

    rtp = gst_element_factory_make("rtpL16pay", "rtpL16pay");
    udp = gst_element_factory_make("udpsink", "udpsink");

    g_object_set( udp, "host", "192.168.1.4", "port", 5000, NULL );

    if (!pipeline || !source || !mad || !convert || !rtp || !udp) {
            g_printerr ("One element could not be created. Exiting.\n");
            return -1;
        }

    /* we add all elements into the pipeline */
    gst_bin_add_many(GST_BIN(pipeline), source, mad, convert, rtp, udp, NULL);

    /* we link the elements together */
    gst_element_link_many (source, mad, convert, rtp, udp, NULL);

    /* Set the pipeline to "playing" state*/
    g_print ("Now playing: %s\n", audioFileName);
    gst_element_set_state (pipeline, GST_STATE_PLAYING);

    /* Iterate */
    g_print ("Running...\n");
    g_main_loop_run (loop);

    /* Stop playback */
    g_print ("Stopping playback\n");
    gst_element_set_state (pipeline, GST_STATE_NULL);

    /* Delete the pipeline */
    g_print ("Deleting pipeline\n");
    gst_object_unref (GST_OBJECT (pipeline));
    g_main_loop_unref (loop);

    return 0;
}

